package com.ruitaowang.admin.view.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.http.HttpRequest;
import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.RoleService;
import com.ruitaowang.account.service.SysPwdService;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.account.service.WalletService;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.utils.QRCode;
import com.ruitaowang.core.utils.RandomUtils;
import com.ruitaowang.core.utils.aliyun.SendSMSHelper;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.*;
import groovy.util.IFileNameFinder;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import tech.lingyi.wx.msg.out.TemplateData;
import tech.lingyi.wx.msg.out.TemplateItem;
import wx.wechat.api.API;
import wx.wechat.api.PayAPI;
import wx.wechat.common.Configure;
import wx.wechat.common.signature.MD5;
import wx.wechat.service.mp.MPService;
import wx.wechat.utils.ExcelException;
import wx.wechat.utils.ExcelUtil;

import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;

/**
 * Created by neal on 11/17/16.
 */
@RestController
public class APIAccountController extends BaseController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private VerifyCodeService verifyCodeService;
    @Autowired
    private RelationsService relationsService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private WxClientCredentialService wxClientCredentialService;
    @Autowired
    private WXUserinfoService wxUserinfoService;
    @Autowired
    private UserProfitService userProfitService;
    @Autowired
    private UserMembersService userMembersService;
    @Autowired
    private MeetingService meetingService;
    @Autowired
    private UserRewardService userRewardService;
    @Autowired
    private WalletCompanyService walletCompanyService;
    @Autowired
    private MeetingUserService meetingUserService;
    @Autowired
    private MeetingUserLinkService meetingUserLinkService;
    @Autowired
    private QRCodeRecordService qrCodeRecordService;
    @Autowired
    private CompanyProfitService companyProfitService;
    @Autowired
    private LocalOrderService localOrderService;
    @Autowired
    private BankCardBagService bankCardBagService;
    @Autowired
    private SysPwdService sysPwdService;
    @Autowired
    private CompanyIndustryService companyIndustryService;
    @Autowired
    private CompanyTypeService companyTypeService;
    @Autowired
    private RoleService roleService;
    @Value("${host.api}")
    private String host;

    @RequestMapping(value = "/api/accounts/profit")
    public String profit(UserProfit userProfit, int page) {
        SysUser user =LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        userProfit.setPage(page);
        userProfit.setUserId(user.getId());
        List<UserProfit> list = userProfitService.selectForPage(userProfit);
        List<UserProfitVO> userProfitVOs = new ArrayList<>();
        UserProfitVO userProfitVO = null;
        SysUser user1 = null;
        if(!ObjectUtils.isEmpty(list)){
           for(UserProfit up : list){
               userProfitVO = new UserProfitVO();
               BeanUtils.copyProperties(up, userProfitVO);
               user1 = sysUserService.selectByPK(user.getId());
               if(!ObjectUtils.isEmpty(user1)){
                   userProfitVO.setNickname(user1.getNickname());
                   userProfitVO.setHeadimgurl(user1.getHeadimgurl());
               }
               userProfitVOs.add(userProfitVO);
           }
        }
        MsgOut o = MsgOut.success(userProfitVOs);
        return this.renderJson(o);
    }

    /**
     * 现金返利明细
     * @param userProfit
     * @param page
     * @return
     */
    @RequestMapping(value = "/api/wap/accounts/moneyProfit")
    public String moneyProfit(UserProfit userProfit, int page,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        userProfit.setOrderBy("ctime desc");
        userProfit.setPage(page);
        userProfit.setUserId(Long.parseLong(userId));
        userProfit.setMoneyType((byte)1);
        List<UserProfit> list = userProfitService.selectUserProfitForPage(userProfit);
        List<UserProfit> listOut = new ArrayList<>();
        for(UserProfit u : list){
            if(u.getOrderType() == -1){
                u.setUserProfit(u.getUserProfit() + u.getMoneyReduce());
            }
            listOut.add(u);
        }
        MsgOut o = MsgOut.success(listOut);
        o.setRecords(userProfit.getRecords());
        o.setTotal(userProfit.getTotal());
        return this.renderJson(o);
    }
    /**
     * 红包返利明细
     * @param userProfit
     * @param page
     * @return
     */
    @RequestMapping(value = "/api/wap/accounts/scoreProfit")
    public String scoreProfit(UserProfit userProfit, int page,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        userProfit.setPage(page);
        userProfit.setUserId(Long.parseLong(userId));
        userProfit.setMoneyType((byte)2);
        List<UserProfit> list = userProfitService.selectUserProfitForPage(userProfit);
        MsgOut o = MsgOut.success(list);
        o.setRecords(userProfit.getRecords());
        o.setTotal(userProfit.getTotal());
        return this.renderJson(o);
    }

    /**
     * 商家收益明细
     * @param companyProfit
     * @param page
     * @return
     */
    @RequestMapping(value = "/api/wap/company/profit")
    public String companyProfit(CompanyProfit companyProfit, int page,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        companyProfit.setOrderBy("ctime desc");
        companyProfit.setPage(page);
        Company company = companyService.selectByCompanyStaff(Long.valueOf(userId));
        companyProfit.setCompanyId(company.getCompanyId());
        List<CompanyProfit> list = companyProfitService.selectForPage(companyProfit);
        List<CompanyProfit> listOut = new ArrayList<>();
        for(CompanyProfit c : list){
            if(c.getOrderType() == -1){
                c.setCompanyProfit(c.getCompanyProfit() + c.getMoneyReduce());
            }
            listOut.add(c);
        }
        MsgOut o = MsgOut.success(listOut);
        o.setRecords(companyProfit.getRecords());
        o.setTotal(companyProfit.getTotal());
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/admin/accunts/selectByPk/{id}")
    public String selectByPk(@PathVariable("id") long id){
        MsgOut msgOut=MsgOut.success(sysUserService.selectByPK(id));
        return renderJson(msgOut);
    }
    @RequestMapping(value = "/api/admin/accounts/profit")
    public String profitForAdmin(UserProfit userProfit, int page) {
        userProfit.setPage(page);
        List<UserProfit> list = userProfitService.selectForPage(userProfit);
        List<UserProfitVO> userProfitVOs = new ArrayList<>();
        UserProfitVO userProfitVO = null;
        SysUser user1 = null;
        if(!ObjectUtils.isEmpty(list)){
            for(UserProfit up : list){
                userProfitVO = new UserProfitVO();
                BeanUtils.copyProperties(up, userProfitVO);
                user1 = sysUserService.selectByPK(up.getUserId());
                if(!ObjectUtils.isEmpty(user1)){
                    userProfitVO.setNickname(user1.getNickname());
                    userProfitVO.setHeadimgurl(user1.getHeadimgurl());
                }
                userProfitVOs.add(userProfitVO);
            }
        }
        MsgOut o = MsgOut.success(userProfitVOs);
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/accounts/bizinfo")
    public String bizInfo() {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Company company = new Company();
        company.setUserId(user.getId());
        List<Company> companies = companyService.select(company);
        boolean isCityUser = false;
        boolean isCoFunder = false;
        boolean isBizUser = false;
        boolean isMicroUser = false;
        boolean isXLUser = false;
        boolean isLocalUser = false;
        //'商家类型\n0 实体店\n1 微商\n2 心理咨询 \n3城市合伙人 \n4梦想合伙人'
        if(!ObjectUtils.isEmpty(companies)){
            for (Company comp : companies) {
                if(comp.getCompanyType() == 6){
                    isCoFunder = true;
                }
                if(comp.getCompanyType() == 4){
                    isBizUser = true;
                }
                if(comp.getCompanyType() == 3){
                    isCityUser = true;
                }
                if(comp.getCompanyType() == 2){
                    isXLUser = true;
                }
                if(comp.getCompanyType() == 1){
                    isMicroUser = true;
                }
                if(comp.getCompanyType() == 0){
                    isLocalUser = true;
                }
            }
        }

        if (isMicroUser){
            user.setUserType((byte) 0);
        }
        if (isXLUser){
            user.setUserType((byte) 0);
        }
        if (isLocalUser){
            user.setUserType((byte) 0);
        }
        if (isBizUser){
            user.setUserType((byte) 3);
            user.setRemark("梦想合伙人");
        }

        if (isCityUser){
            user.setUserType((byte) 4);
            user.setRemark("城市合伙人");
        }

        if (isCoFunder){ //王 按照梦想合伙人走 user.getId() == 11198
            user.setUserType((byte) 6);
            user.setRemark("联合创始人");
        }

        if(user.getId() == 11198){
            user.setUserType((byte) 6);
            user.setRemark("联合创始人");
        }

        MsgOut o = MsgOut.success(user);
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/accounts/info")
    public String userInfo() {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        user = sysUserService.selectByPK(user.getId());
        if (StringUtils.isEmpty(user.getQrimgurl())) {
            //generate qr
            user.setQrimgurl(QRCode.rulesQRForUserId(System.getProperty("catalina.base"), user.getId()));
            sysUserService.update(user);
            user.setPassword("");
        }
        Company company=new Company();
        company.setUserId(user.getId());
        company.setCompanyType((byte)11);
        List<Company> companies=companyService.select(company);
        if (!ObjectUtils.isEmpty(companies)){
            if (companies.get(0).getCompanyStatus() == 1){
                user.setMtime(companies.get(0).getCompanyId());
            }else {
                user.setMtime(-2L);
            }
        }else {
            Company c=new Company();
            c.setUserId(user.getId());
            c.setCompanyType((byte)13);
            List<Company> companyList=companyService.select(c);
            if (!ObjectUtils.isEmpty(companyList)){
                if (companyList.get(0).getCompanyStatus() == 1){
                    user.setMtime(companyList.get(0).getCompanyId());
                }else {
                    user.setMtime(-2L);
                }
            }else {
                user.setMtime(-1L);
            }
        }
        MsgOut o = MsgOut.success(user);
        return this.renderJson(o);
    }

    /**
     * 获取当前登陆者的详细信息
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/accounts/info")
    public String wapUserInfo(@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser user = sysUserService.selectByPK(Long.parseLong(userId));
        if (StringUtils.isEmpty(user.getQrimgurl())) {
            //generate qr
            user.setQrimgurl(QRCode.rulesQRForUserId(System.getProperty("catalina.base"), user.getId()));
            sysUserService.update(user);
            user.setPassword("");
        }
        SysUserVO sysUserVO=new SysUserVO();
        BeanUtils.copyProperties(user,sysUserVO);
        QRCodeRecord qrCodeRecord =  new QRCodeRecord();
        qrCodeRecord.setUserId(sysUserVO.getId());
        qrCodeRecord.setBuyStatus((byte)2);
        List<QRCodeRecord> qrCodeRecords=qrCodeRecordService.select(qrCodeRecord);
        if (ObjectUtils.isEmpty(qrCodeRecords)){
            sysUserVO.setQrPay((byte) 1);
        }else {
            sysUserVO.setQrPay((byte)2);
        }
        List<QRCodeRecordVO> selectForBh = qrCodeRecordService.selectForBh(qrCodeRecord);
        if (ObjectUtils.isEmpty(selectForBh)){
            sysUserVO.setSelectForBh("");
        } else {
            sysUserVO.setSelectForBh("H00" + selectForBh.get(0).getGjBh());
        }
        MsgOut o = MsgOut.success(sysUserVO);
        return this.renderJson(o);
    }

    /**
     * 直推1级 人员列表
     * @param page
     * @param relations
     * @return
     */
    @RequestMapping(value = "/api/wap/child/level1")
    public String wapUserChildLevel1(int page,Relations relations,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        List listOut = new ArrayList();
        relations.setPage(page);
        relations.setPid(Long.parseLong(userId));
        List<Relations> relationsList=relationsService.selectForPage(relations);
        for (Relations r:relationsList){
              SysUser sysUser=sysUserService.selectByPK(r.getUesrId());
              if (!ObjectUtils.isEmpty(sysUser)){
                  sysUser.setCtime(r.getCtime());
                  listOut.add(sysUser);
              }
        }
        MsgOut o = MsgOut.success(listOut);
        o.setRecords(relations.getRecords());
        o.setTotal(relations.getTotal());
        return this.renderJson(o);
    }

    /**
     * 间推2级 人员列表
     * @param page
     * @param relations
     * @return
     */
    @RequestMapping(value = "/api/wap/child/level2")
    public String wapUserChildLevel2(int page,Relations relations,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        List listOut = new ArrayList();
        relations.setPage(page);
        relations.setPid(Long.parseLong(userId));
        List<Relations> relationsList=relationsService.selectALLChildsTwoForPage(relations);
        for (Relations r:relationsList){
            SysUser sysUser=sysUserService.selectByPK(r.getUesrId());
            if (!ObjectUtils.isEmpty(sysUser)){
                sysUser.setCtime(r.getCtime());
                listOut.add(sysUser);
            }
        }
        MsgOut o = MsgOut.success(listOut);
        o.setRecords(relations.getRecords());
        o.setTotal(relations.getTotal());
        return this.renderJson(o);
    }

    /**
     * 个人中心 推荐人 详情
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/user/superior")
    public String wapUserSuperior(@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser sysUser = new SysUser();
        Relations relations=relationsService.selectByPK(Long.parseLong(userId));
        if (ObjectUtils.isEmpty(relations)){
            return this.renderJson(MsgOut.error("此用户 查询不到上级"));
        }else {
            sysUser=sysUserService.selectByPK(relations.getPid());
            sysUser.setCtime(relations.getCtime());
        }
        MsgOut o = MsgOut.success(sysUser);
        o.setRecords(relations.getRecords());
        o.setTotal(relations.getTotal());
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/accounts/member/limit")
    public String memberLimit() {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        UserMembers where = new UserMembers();
        where.setUserId(user.getId());

        return this.renderJson(MsgOut.success(userMembersService.select(where)));
    }

    /**
     * 获取登陆者基础信息
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/accounts/myself")
    public String myself(@RequestHeader(value="headId",required = false) String userId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user) && ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser sysUser = new SysUser();
        if (ObjectUtils.isEmpty(user)){
            sysUser=sysUserService.selectByPK(Long.parseLong(userId));
        }else if (ObjectUtils.isEmpty(userId)){
            sysUser=sysUserService.selectByPK(user.getId());
        }
        return this.renderJson(MsgOut.success(sysUser));
    }

    @RequestMapping(value = "/api/accounts/member/limit/check")
    public String checkMemberLimit() {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if(ObjectUtils.isEmpty(userMembersService.getMemberForKSLimit(user.getId()))){
            return this.renderJson(MsgOut.success());
        }else{
            return this.renderJson(MsgOut.error(":(-"));
        }

    }

    @RequestMapping(value = "/api/accounts/direct")//direct invite
    public String direct() {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Relations relations = relationsService.selectByPK(user.getId());
        if (StringUtils.isEmpty(relations)) {
            //generate qr
            return this.renderJson(MsgOut.error());
        }
        user = sysUserService.selectByPK(relations.getPid());
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error());
        }
        user.setPassword("");
        MsgOut o = MsgOut.success(user);
        return this.renderJson(o);
    }

    /**
     * 是否关注公众号
     * @return
     */
    @RequestMapping(value = {"/api/wx/subscribe"})
    public String subscribe() {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SNSWXUserinfo userinfo = wxUserinfoService.selectByPK(user.getId());
        SysUser sysUser=sysUserService.selectByPK(user.getId());
        try {
            MPService mpService = new MPService();
            Map<String, String> map = mpService.fetchAccessToken4ClientCredential();
            WxClientCredentail wxClientCredentail = new WxClientCredentail();
            wxClientCredentail.setAccessToken(map.get("access_token").toString());
            wxClientCredentail.setExpiresIn(Integer.valueOf(map.get("expires_in").toString()));
            wxClientCredentialService.insert(wxClientCredentail);
            Map<String, String> map1 = mpService.fetchUserinfoByAccessTokenAndOpenId(wxClientCredentail.getAccessToken(), userinfo.getOpenid());

            //更新数据库，用户是否关注公众号
            if (Byte.parseByte(map1.get("subscribe")) != sysUser.getSubscribe()){
                sysUser.setSubscribe(Byte.parseByte(map1.get("subscribe")));
                sysUserService.update(sysUser);
            }
            return this.renderJson(MsgOut.success(map1));

        } catch (IOException e) {
            LOGGER.error("getToken {}", e);
        }
        return this.renderJson(MsgOut.error());
    }

    @RequestMapping(value = {"/api/wx/Allsubscribe"})
    public String Allsubscribe() {
        SysUser sysUser = new SysUser();
        List<SysUser> sysUserList = sysUserService.select(sysUser);
        for(SysUser s : sysUserList){
            SNSWXUserinfo userinfo = wxUserinfoService.selectByPK(s.getId());
            try {
                MPService mpService = new MPService();
                Map<String, String> map = mpService.fetchAccessToken4ClientCredential();
                WxClientCredentail wxClientCredentail = new WxClientCredentail();
                wxClientCredentail.setAccessToken(map.get("access_token").toString());
                wxClientCredentail.setExpiresIn(Integer.valueOf(map.get("expires_in").toString()));
                wxClientCredentialService.insert(wxClientCredentail);
                Map<String, String> map1 = mpService.fetchUserinfoByAccessTokenAndOpenId(wxClientCredentail.getAccessToken(), userinfo.getOpenid());

                //更新数据库，用户是否关注公众号
                if (Byte.parseByte(map1.get("subscribe")) != sysUser.getSubscribe()){
                    sysUser.setSubscribe(Byte.parseByte(map1.get("subscribe")));
                    sysUserService.update(sysUser);
                }
                return this.renderJson(MsgOut.success(map1));

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return this.renderJson(MsgOut.error());
    }

    /**
     * 共享通 验证用户是否关注公众号
     * @param userId
     * @return
     */
    @RequestMapping(value = {"/api/wap/wx/subscribe"})
    public String wapSubscribe(@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }

        SNSWXUserinfo userinfo = wxUserinfoService.selectByPK(Long.parseLong(userId));
        SysUser sysUser=sysUserService.selectByPK(Long.parseLong(userId));
        try {
            MPService mpService = new MPService();
            Map<String, String> map = mpService.fetchAccessToken4ClientCredential();
            WxClientCredentail wxClientCredentail = new WxClientCredentail();
            wxClientCredentail.setAccessToken(map.get("access_token").toString());
            wxClientCredentail.setExpiresIn(Integer.valueOf(map.get("expires_in").toString()));
            wxClientCredentialService.insert(wxClientCredentail);
            Map<String, String> map1 = mpService.fetchUserinfoByAccessTokenAndOpenId(wxClientCredentail.getAccessToken(), userinfo.getOpenid());

            //更新数据库，用户是否关注公众号
            if (Byte.parseByte(map1.get("subscribe")) != sysUser.getSubscribe()){
                sysUser.setSubscribe(Byte.parseByte(map1.get("subscribe")));
                sysUserService.update(sysUser);
            }
            return this.renderJson(MsgOut.success(map1));

        } catch (IOException e) {
            LOGGER.error("getToken {}", e);
        }
        return this.renderJson(MsgOut.error());
    }
    @RequestMapping(value = "/api/accounts/smpay/{fromUserIdOtherID}")
    public String smPayInfo(@PathVariable String fromUserIdOtherID) {
        if (ObjectUtils.isEmpty(fromUserIdOtherID)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        String[] iDs = fromUserIdOtherID.split("-");
        if (ObjectUtils.isEmpty(iDs) || iDs.length < 4) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser user = sysUserService.selectByPK(Long.valueOf(iDs[2]));
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
//        Company company = new Company();
//        company.setUserId(Long.valueOf(iDs[3]));
        Company company = companyService.selectByPK(Long.valueOf(iDs[3]));
        if (ObjectUtils.isEmpty(company)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        return this.renderJson(MsgOut.success(company));
    }
@RequestMapping(value = "/api/admin/accounts/friends")
public String friendsForAdmin(Relations relations, int page) {
    SysUser user = LYSecurityUtil.currentSysUser();
    if (ObjectUtils.isEmpty(user)) {
        return this.renderJson(MsgOut.error("Plz login."));
    }
    relations.setPage(page);
    relations.setOrderBy("uesr_id desc");
    List<Relations> list = relationsService.selectAllChildForPage(relations);
    if(ObjectUtils.isEmpty(list)){
        return this.renderJson(MsgOut.error("no data"));
    }
    List<Long> users = new ArrayList<>();
    for (int i = 0; i < list.size(); i++) {
        users.add(list.get(i).getUesrId());
//        if( relations.getUesrId() == 11423 && page == 10){
//            users.add(61542L);
//            List<Long> listTS = relationsService.selectAllChild(61542L);
//            if(!ObjectUtils.isEmpty(listTS)){
//                users.addAll(listTS);
//            }
//        }
    }
    MsgOut o = MsgOut.success(relationsService.selectALLFriends(users));
    o.setRecords(relations.getRecords());
    o.setTotal(relations.getTotal());
    return this.renderJson(o);
}

    /**
     * 10级好友，废弃
     * @param relations
     * @param page
     * @return
     */
    @RequestMapping(value = "/api/accounts/friends")
    public String friends(Relations relations, int page) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        relations.setPage(page);
        relations.setUesrId(user.getId());
        relations.setOrderBy("uesr_id desc");
        List<Relations> list = relationsService.selectAllChildForPage(relations);
        if(ObjectUtils.isEmpty(list)){
            return this.renderJson(MsgOut.error("no data"));
        }
        List<Long> users = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            users.add(list.get(i).getUesrId());
            if( relations.getUesrId() == 11423 && page == 10){
                users.add(61542L);
                List<Long> listTS = relationsService.selectAllChild(61542L);
                if(!ObjectUtils.isEmpty(listTS)){
                    users.addAll(listTS);
                }
            }
        }

        MsgOut o = MsgOut.success(relationsService.selectALLFriends(users));
        o.setRecords(relations.getRecords());
        o.setTotal(relations.getTotal());
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/wap/accounts/friends/level1")
    public String friendsLevel1(Relations relations, int page) {
//        SysUser user = this.currentUser();
//        if (ObjectUtils.isEmpty(user)) {
//            return this.renderJson(MsgOut.error("Plz login."));
//        }
        relations.setPage(page);
        relations.setOrderBy("uesr_id desc");
        List<SysUser> list = relationsService.selectLevel1ChildForPage(relations);
        if(ObjectUtils.isEmpty(list)){
            return this.renderJson(MsgOut.error("no data"));
        }

        MsgOut o = MsgOut.success(list);
        o.setRecords(relations.getRecords());
        o.setTotal(relations.getTotal());
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/accounts/wallet")
    public String userWallet(){
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        MsgOut o = MsgOut.success(walletService.selectByPK(user.getId()));
        return this.renderJson(o);
    }

    /**
     * wap 查询个人钱包
     * @param userId
     * @return
     */
    @RequestMapping("/api/wallet")
    public String list(@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        Wallet wallet = new Wallet();
        Wallet w=walletService.selectByPK(Long.parseLong(userId));
        if (ObjectUtils.isEmpty(w)){
            wallet.setUserId(Long.parseLong(userId));
            wallet.setUserBalance(0);
            wallet.setUserScore(0);
            walletService.insert(wallet);
        }else {
            wallet = w;
        }
        MsgOut o = MsgOut.success(wallet);
        return this.renderJson(o);
    }

    /**
     * 分页查询钱包
     * @param wallet
     * @param page
     * @return
     */
    @RequestMapping("/api/admin/wallet")
    public String adminList(Wallet wallet, int page) {
        if (!ObjectUtils.isEmpty(wallet.getSidx())) {
            wallet.setOrderBy(wallet.getSidx() + " " + wallet.getSord() + "," + wallet.getOrderBy());
        }
        wallet.setPage(page);
        List<Wallet> wallets=walletService.selectForPage(wallet);
        MsgOut o = MsgOut.success(wallets);
        o.setRecords(wallet.getRecords());
        o.setTotal(wallet.getTotal());
        return this.renderJson(o);
    }
    /**
     * 个人中心钱包
     * @return
     */
    @RequestMapping("/api/wap/wallet")
    public String wapList(@RequestHeader(value="headId",required = false) String userId) {
        SysUser user = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user) && ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if(ObjectUtils.isEmpty(user)){
            user.setId(Long.valueOf(userId));
            LOGGER.info("此时的userId为空，userId == " + user.getId());
        } else {
            LOGGER.info("正常的userId，userId == " + user.getId());
        }
        Wallet wallet=walletService.selectByPK(user.getId());
        if (ObjectUtils.isEmpty(wallet)){
            wallet = new Wallet();
            wallet.setUserId(user.getId());
            walletService.insert(wallet);
        }
        MsgOut o = MsgOut.success(wallet);
        return this.renderJson(o);
    }

    /**
     * 注册
     *
     * @param username
     * @param checkcode
     * @param agree
     * @return
     */
    @RequestMapping(value = "/api/accounts/register", method = RequestMethod.POST)
    public String register(String username, String checkcode, String agree) {
        if (!StringUtils.hasLength(username) ||
                !StringUtils.hasLength(checkcode) ||
                !StringUtils.hasLength(agree) ||
                !"on".equals(agree)) {
            return this.renderJson(MsgOut.error());
        }
        String codeCache = "123";
        //检测全局缓存中的code与传过来的code是否匹配
        if (!checkcode.equals(codeCache)) {
            return this.renderJson(MsgOut.error("验证码错误！"));
        }
        SysUser sysUser = new SysUser();
        sysUser.setPhone(username);
        //检测手机号是否注册过
        List<SysUser> sysUserList = sysUserService.select(sysUser);
        if (sysUserList != null && sysUserList.size() > 0) {
            return this.renderJson(MsgOut.error("该手机号已经注册过龙蛙网！"));
        }
        sysUser.setUsername(username);
        //发送密码短信
        String password = RandomStringUtils.randomAlphanumeric(6);
        LOGGER.info("passwrod {}", password);
        sysUser.setPassword(RandomUtils.hashPassword(password));
        sysUser.setLastIp(API.getClientIpAddress(this.getRequest()));
        sysUser.setLastTime(System.currentTimeMillis());
        sysUserService.insert(sysUser);
        return this.renderJson(MsgOut.success());
    }

    /**
     * 设置交易密码
     * @param passWord
     * @param phone
     * @param checkcode
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/accounts/passWord", method = RequestMethod.POST)
    public String wapTransactionPwd(String passWord,String phone,String checkcode,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser sysUser = sysUserService.selectByPK(Long.parseLong(userId));
    	String sysPhone = sysUser.getPhone();
    	if(!phone.equals(sysPhone)) {
    		return this.renderJson(MsgOut.error("请输入已绑定手机号！"));
    	}
        //检测验证码是否有效
        Verifycode v = new Verifycode();
        v.setMobile(phone);
        List<Verifycode> verifycodes = verifyCodeService.select(v);
        if (ObjectUtils.isEmpty(verifycodes)) {
            return this.renderJson(MsgOut.error("请输入验证码！"));
        }
        v = verifycodes.get(0);
        //检测全局缓存中的code与传过来的code是否匹配
        if (!checkcode.equals(v.getVerifycode())) {
            return this.renderJson(MsgOut.error("验证码错误！"));
        }
        //设置密码
        SysPwd sysPwd=sysPwdService.selectByPK(Long.parseLong(userId));
        if (ObjectUtils.isEmpty(sysPwd)){
            SysPwd pwd=new SysPwd();
            pwd.setUserId(Long.parseLong(userId));
            pwd.setUserPwd(MD5.MD5Encode(passWord));
            sysPwdService.insert(pwd);
        }else {
            return this.renderJson(MsgOut.error("以设置交易密码，请勿重复提交"));
        }
        return this.renderJson(MsgOut.success("设置成功"));
    }
    
   /**
    * 修改交易密码
    * @param passWord
    * @param phone
    * @param checkcode
    * @param userId
    * @return
    */
    @RequestMapping(value = "/api/wap/accounts/passWord", method = RequestMethod.PUT)
    public String wapUpdatePwd(String passWord,String phone,String checkcode,@RequestHeader(value="headId",required = false) String userId) {
    	if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
    	SysUser sysUser = sysUserService.selectByPK(Long.parseLong(userId));
    	String sysPhone = sysUser.getPhone();
    	if(!phone.equals(sysPhone)) {
    		return this.renderJson(MsgOut.error("请输入已绑定手机号！"));
    	}
    	
        //检测验证码是否有效
        Verifycode v = new Verifycode();
        v.setMobile(phone);
        List<Verifycode> verifycodes = verifyCodeService.select(v);
        if (ObjectUtils.isEmpty(verifycodes)) {
            return this.renderJson(MsgOut.error("请输入验证码！"));
        }
        v = verifycodes.get(0);
        //检测全局缓存中的code与传过来的code是否匹配
        if (!checkcode.equals(v.getVerifycode())) {
            return this.renderJson(MsgOut.error("验证码错误！"));
        }
        SysPwd sysPwd=new SysPwd();
    	sysPwd.setUserId(Long.parseLong(userId));
        sysPwd.setUserPwd(MD5.MD5Encode(passWord));
        sysPwdService.update(sysPwd);
        return this.renderJson(MsgOut.success("修改成功！"));
    }

    /**
     * 用户更改手机号
     * @param sysUser
     * @param checkcode
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/phone", method = RequestMethod.PUT)
    public String wapUpdatePhone(SysUser sysUser,String checkcode,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        //检测验证码是否有效
        Verifycode v = new Verifycode();
        v.setMobile(sysUser.getPhone());
        List<Verifycode> verifycodes = verifyCodeService.select(v);
        if (ObjectUtils.isEmpty(verifycodes)) {
            return this.renderJson(MsgOut.error("请输入验证码！"));
        }
        v = verifycodes.get(0);
        //检测全局缓存中的code与传过来的code是否匹配
        if (!checkcode.equals(v.getVerifycode())) {
            return this.renderJson(MsgOut.error("验证码错误！"));
        }
        sysUser.setId(Long.parseLong(userId));
        sysUserService.update(sysUser);
        return this.renderJson(MsgOut.success("修改手机号成功！"));
    }

    /**
     * 密码校验
     * @param passWord
     * @return
     */
    @RequestMapping(value = "/api/wap/accounts/validatePwd", method = RequestMethod.POST)
    public String validatePwd(String passWord,@RequestHeader(value="headId",required = false) String userId) {
        SysUser sysUser = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(sysUser) && ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        long id;
        if (ObjectUtils.isEmpty(userId)){
            id=sysUser.getId();
        }else {
            id=Long.parseLong(userId);
        }
        SysPwd sysPwd=sysPwdService.selectByPK(id);
        if (ObjectUtils.isEmpty(sysPwd)){
            return this.renderJson(MsgOut.error("该用户未设置交易密码"));
        }
        String pwd = MD5.MD5Encode(passWord);
        if (sysPwd.getUserPwd().equals(pwd)){
            return this.renderJson(MsgOut.success("密码校验成功"));
        }else {
            return this.renderJson(MsgOut.error("密码校验失败"));
        }
    }

    /**
     * 验证是否已经设置密码
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/accounts/sysPwd", method = RequestMethod.GET)
    public String wapValidatePwd(@RequestHeader(value="headId",required = false) Long userId) {
        SysUser sysUser = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(userId) && ObjectUtils.isEmpty(sysUser)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if(ObjectUtils.isEmpty(userId) && !ObjectUtils.isEmpty(sysUser)){
            userId = sysUser.getId();
        }
        //SysPwd sysPwd=sysPwdService.selectByPK(Long.parseLong(userId));
        SysPwd sysPwd=sysPwdService.selectByPK(userId);
        if (!ObjectUtils.isEmpty(sysPwd)){
            String userPwd = sysPwd.getUserPwd();
            if (ObjectUtils.isEmpty(userPwd)){
                return this.renderJson(MsgOut.error("该用户未设置交易密码"));
            }else {
                return this.renderJson(MsgOut.success("该用户以设置交易密码"));
            }
        }
        return this.renderJson(MsgOut.error("系统进入到外太空，用户可能未设置密码！"));
    }
    /**
     * 忘记密码
     *
     * @param username
     * @param checkcode
     * @return
     */
    @RequestMapping(value = "/api/accounts/forgetPassword", method = RequestMethod.POST)
    public String forgetPassword(String username, String checkcode) {

        if (!StringUtils.hasLength(username) ||
                !StringUtils.hasLength(checkcode)) {
            return this.renderJson(MsgOut.error());
        }

        String codeCache = "123";
        //检测全局缓存中的code与传过来的code是否匹配
        if (!checkcode.equals(codeCache)) {
            return this.renderJson(MsgOut.error("验证码错误！"));
        }

        SysUser sysUser = new SysUser();
        sysUser.setPhone(username);
        //检测手机号是否注册过
        List<SysUser> sysUserList = sysUserService.select(sysUser);
        if (sysUserList == null || sysUserList.size() == 0) {
            return this.renderJson(MsgOut.error("该手机号没有注册过龙蛙网！"));
        }
        //发送密码短信
        String password = RandomStringUtils.randomAlphanumeric(6);
        LOGGER.info("passwrod {}", password);
        sysUser.setPassword(RandomUtils.hashPassword(password));
        sysUser.setLastIp(API.getClientIpAddress(this.getRequest()));
        sysUser.setLastTime(System.currentTimeMillis());
        sysUserService.update(sysUser);
        return this.renderJson(MsgOut.success("新密码已发送到您的手机"));
    }

    /**
     * 获取短信验证码
     *
     * @param username
     * @return
     */
    @RequestMapping(value = "/api/accounts/checkcode")
    public String checkcode(String username, String random) {//TODO:图片验证码
        if (StringUtils.isEmpty(username)) {
            return this.renderJson(MsgOut.error("手机号不能为空"));
        }

        //check exists
        Verifycode verifycode = new Verifycode();
        verifycode.setMobile(username);
        long now = Instant.now().getEpochSecond();
        List<Verifycode> verifycodes = verifyCodeService.select(verifycode);
        if (ObjectUtils.isEmpty(verifycodes)) {
            //storage to db
            verifycode.setRegIp(API.getClientIpAddress(this.getRequest()));
            verifycode.setInviteCount(1);
            String randomCode = RandomUtils.randomString(6);
            verifycode.setVerifycode(String.valueOf(randomCode));
            try {
                SendSMSHelper.sendSMS(username, randomCode);
            } catch (Exception e) {
                e.printStackTrace();
                return this.renderJson(MsgOut.error("发送短信异常"));
            }
            verifycode.setRegDeadline(now + 30 * 60);
            verifyCodeService.insert(verifycode);
            return this.renderJson(MsgOut.success());
        }

        //exists
        //check deadline
        verifycode = verifycodes.get(0);
        if (verifycode.getRegDeadline() - now > 0) {
            return this.renderJson(MsgOut.success("已经发送到您的手机。"));
        }

        //check ip
        String ip = verifycode.getRegIp();
        Verifycode v = new Verifycode();
        v.setRegIp(ip);
        v.setCtime((now - 60 * 60 * 2) * 1000);
        int count = verifyCodeService.count(v);

        if (count > 500) {
            return this.renderJson(MsgOut.error("ip异常"));
        }

        verifycode.setMtime(now);
        verifycode.setRegIp(PayAPI.getClientIpAddress(this.getRequest()));

        verifycode.setInviteCount(verifycode.getInviteCount() + 1);
        String randomCodeNew = RandomUtils.randomString(6);
        verifycode.setVerifycode(String.valueOf(randomCodeNew));
        LOGGER.error("verifycode -----------> ", JSON.toJSONString(verifycode));
        try {
            SendSMSHelper.sendSMS(username, randomCodeNew);
        } catch (Exception e) {
            e.printStackTrace();
            return this.renderJson(MsgOut.error("发送短信异常"));
        }
        LOGGER.error("verifycode -----------> ", JSON.toJSONString(verifycode));
        verifycode.setRegDeadline(now + 30 * 60);
        verifyCodeService.update(verifycode);
        return this.renderJson(MsgOut.success("已经发送到您的手机。"));
    }

    /**
     * 绑定手机号 登录时
     *
     * @param username
     * @param checkcode
     * @return
     */
    @RequestMapping(value = "/api/accounts/bindMobile", method = RequestMethod.POST)
    public String bindMobile(String username, String password, String checkcode,String wechatId,@RequestHeader(value="headId",required = false) String userId) {
        SysUser user =LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(userId) && ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(checkcode) ||
                StringUtils.isEmpty(password)) {
            return this.renderJson(MsgOut.error());
        }

        Verifycode v = new Verifycode();
        v.setMobile(username);
        List<Verifycode> verifycodes = verifyCodeService.select(v);
        if (ObjectUtils.isEmpty(verifycodes)) {
            return this.renderJson(MsgOut.error("请输入验证码！"));
        }
        v = verifycodes.get(0);
        //检测全局缓存中的code与传过来的code是否匹配
        if (!checkcode.equals(v.getVerifycode())) {
            return this.renderJson(MsgOut.error("验证码错误！"));
        }

        SysUser sysUser = new SysUser();
        sysUser.setPhone(username);
        //检测手机号是否注册过
        List<SysUser> sysUserList = sysUserService.select(sysUser);
        if (!ObjectUtils.isEmpty(sysUserList)) {
            return this.renderJson(MsgOut.error("该手机号已经注册过龙蛙网！"));
        }

        //发送密码短信
        sysUser.setUsername(username);
        password = username;
        sysUser.setPassword(RandomUtils.hashPassword(password));
        sysUser.setLastIp(API.getClientIpAddress(this.getRequest()));
        sysUser.setLastTime(System.currentTimeMillis());
        //long pid;
        if(ObjectUtils.isEmpty(userId)){
            sysUser.setId(user.getId());
            //Relations relations = relationsService.selectByPK(user.getId());
            //pid = relations.getPid();      //获取上级Id
        } else {
            sysUser.setId(Long.parseLong(userId));
            //Relations relations = relationsService.selectByPK(Long.parseLong(userId));
            //pid = relations.getPid();      //获取上级Id
        }
        if (!StringUtils.isEmpty(wechatId)){
            sysUser.setWechatId(wechatId);
        }
        sysUserService.update(sysUser);
//        Relations relations = new Relations();
//        relations.setPid(pid);
//        List<Relations> relationsList = relationsService.select(relations);
//        int personCount = 0;    //下级绑定手机号的个数
//        for(Relations rl : relationsList){
//            SysUser sysUser1 = sysUserService.selectByPK(rl.getUesrId());
//            String phone = sysUser1.getPhone();
//            if (!ObjectUtils.isEmpty(phone)) {
//                personCount++;
//            }
//        }
//        if(personCount == 100){
//            UserMembers userMembers = new UserMembers();
//            userMembers.setUserId(pid);
//            userMembers.setRstatus((byte)0);
//            userMembers.setMemberType((byte)1);
//            List<UserMembers> userMembersList = userMembersService.select(userMembers);
//            UserMembers userMembers1 = userMembersList.get(0);
//            userMembers1.setPermanent((byte)1);
//            //赠送永久微传媒权限
//            userMembersService.update(userMembers1);
//            return this.renderJson(MsgOut.success());
//        } else if(personCount > 100){
//            return this.renderJson(MsgOut.success());
//        }
//        //赠送1个月微传媒权限
//        userMembersService.setUserMembersLimit(30, pid, (byte) 1);
        return this.renderJson(MsgOut.success());
    }

//    /**
//     * 为老用户赠送微传媒
//     * @param userId
//     * @return
//     */
//    @Transactional
//    @RequestMapping(value = "/api/accounts/insertOld", method = RequestMethod.PUT)
//    public String insertOld(@RequestHeader(value="headId",required = false) String userId) {
//        if (ObjectUtils.isEmpty(userId)) {
//            return this.renderJson(MsgOut.error("Plz login."));
//        }
////        SysUser sysUser = new SysUser();
//        List<Role> roles = roleService.selectByPid();
//        for (Role rl : roles){
//            Long pid = rl.getPid();
//            Relations relations = new Relations();
//            relations.setPid(pid);
//            List<Relations> relationsList = relationsService.select(relations);
//            int personCount=0;
//            for (Relations r:relationsList){
//                if (r.getCtime() < 1540857600000L){
//                    personCount += 1;
//                }
//            }
////            int personCount = relationsList.size();//下级的个数
//            if(personCount >= 100){
//                UserMembers userMembers = new UserMembers();
//                userMembers.setUserId(pid);
//                userMembers.setRstatus((byte)0);
//                userMembers.setMemberType((byte)1);
//                List<UserMembers> userMembersList = userMembersService.select(userMembers);
//                if (ObjectUtils.isEmpty(userMembersList)) {
//                    UserMembers userMembers1 = new UserMembers();
//                    userMembers1.setUserId(pid);
//                    userMembers1.setRstatus((byte)0);
//                    userMembers1.setMemberType((byte)1);
//                    userMembers1.setPermanent((byte)1);
//                    userMembers1.setEndTime("2018-10-30");
//                    //赠送永久微传媒权限
//                    userMembersService.insert(userMembers1);
//                } else {
//                    UserMembers userMembers1 = userMembersList.get(0);
//                    userMembers1.setPermanent((byte)1);
//                    //赠送永久微传媒权限
//                    userMembersService.update(userMembers1);
//                }
//            }else {
//                UserMembers userMembers = new UserMembers();
//                userMembers.setUserId(pid);
//                userMembers.setRstatus((byte)0);
//                userMembers.setMemberType((byte)1);
//                List<UserMembers> userMembersList = userMembersService.select(userMembers);
//                if (ObjectUtils.isEmpty(userMembersList)) {
//                    UserMembers userMembers1 = new UserMembers();
//                    userMembers1.setUserId(pid);
//                    userMembers1.setRstatus((byte)0);
//                    userMembers1.setMemberType((byte)1);
//                    userMembers1.setEndTime("2018-10-30");
////                    userMembers1.setPermanent((byte)1);
//                    //赠送永久微传媒权限
//                    userMembersService.insert(userMembers1);
//                }
//                userMembersService.setUserMembersForKZ1Limit(personCount,pid);
////                else {
////                    UserMembers userMembers1 = userMembersList.get(0);
////                    userMembers1.setPermanent((byte)1);
////                    //赠送永久微传媒权限
////                    userMembersService.update(userMembers1);
////                }
//            }
//        }
//        return this.renderJson(MsgOut.success());
//    }

    /**
     * 绑定手机号 签到 不需要密码
     *
     * @param username
     * @param checkcode
     * @return
     */
    @RequestMapping(value = "/api/accounts/bindMobile2", method = RequestMethod.POST)
    public String bindMobile2(String username, String checkcode) {
        SysUser user =LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error("请先登录"));
        }
        if (StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(checkcode) ) {
            return this.renderJson(MsgOut.error());
        }

        Verifycode v = new Verifycode();
        v.setMobile(username);
        List<Verifycode> verifycodes = verifyCodeService.select(v);
        if (ObjectUtils.isEmpty(verifycodes)) {
            return this.renderJson(MsgOut.error("请输入验证码！"));
        }
        v = verifycodes.get(0);
        //检测全局缓存中的code与传过来的code是否匹配
        if (!checkcode.equals(v.getVerifycode())) {
            return this.renderJson(MsgOut.error("验证码错误！"));
        }

        SysUser sysUser = new SysUser();
        sysUser.setPhone(username);
        //检测手机号是否注册过
        List<SysUser> sysUserList = sysUserService.select(sysUser);
        if (ObjectUtils.isEmpty(sysUserList)) {//没有绑定过
            sysUser.setPassword(RandomUtils.hashPassword(username));
        }else{

        }
        sysUser.setUsername(username);
        sysUser.setLastIp(API.getClientIpAddress(this.getRequest()));
        sysUser.setLastTime(System.currentTimeMillis());
        sysUser.setId(user.getId());
        sysUserService.update(sysUser);

        //确认签到
        //1，判断此人是否报名
        MeetingUser meetingUser = meetingUserService.selectByPhone(username);
        if (ObjectUtils.isEmpty(meetingUser)) {
            return this.renderJson(MsgOut.error("您还没有报名！"));
        }

        //2，若报名，变更 为已签到meeting_user_link rstatus
        MeetingUserLink meetingUserLink = meetingUserLinkService.selectByPhone(username);
        if (ObjectUtils.isEmpty(meetingUserLink)) {
            return this.renderJson(MsgOut.error("签到失败！"));
        }

        //3， 重复签到
        meetingUserLink = meetingUserLinkService.selectByPhone(username);
        if (meetingUserLink.getRstatus() == 1) {
            return this.renderJson(MsgOut.success("-1"));
        }
        meetingUserLinkService.delete(meetingUserLink.getLinkId());
        return this.renderJson(MsgOut.success());
    }

    /**
     * 预报名
     *
     * @param meetingUser
     * @return
     */
    @RequestMapping(value = "/api/accounts/joinMeeting", method = RequestMethod.POST)
    public String joinMeeting(MeetingUser meetingUser) {
        SysUser sysUser = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(sysUser)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }

        if (StringUtils.isEmpty(meetingUser.getRealName()) ||
                StringUtils.isEmpty(meetingUser.getMeetingId()) ||
                StringUtils.isEmpty(meetingUser.getPhone()) ) {
            return this.renderJson(MsgOut.error());
        }

        sysUser.setRealName(meetingUser.getRealName());
        sysUser.setIdCard(meetingUser.getIdCard());
        sysUser.setLastIp(API.getClientIpAddress(this.getRequest()));
        sysUser.setLastTime(System.currentTimeMillis());
        sysUserService.update(sysUser);

        if(ObjectUtils.isEmpty(meetingUserService.selectByPhone(meetingUser.getPhone()))){
            meetingUserService.insert(meetingUser);
        }

        MeetingUserLink userMeetingsLink = new MeetingUserLink();
        userMeetingsLink.setMeetingId(meetingUser.getMeetingId());
        userMeetingsLink.setUserId(sysUser.getId());
        userMeetingsLink.setPhone(meetingUser.getPhone());
        userMeetingsLink = meetingService.insertOrUpdateMeetingForSignUp(userMeetingsLink);
        if(userMeetingsLink.getRstatus() == -1){
            return this.renderJson(MsgOut.error("您已经报过名了 ：）～"));
        }
        return this.renderJson(MsgOut.success());
    }

    /**
     * 判断是否报名
     *
     * @param meetingId
     * @return
     * Abort
     */
    @RequestMapping(value = "/api/accounts/signInMeeting")
    public String signInMeeting(Long meetingId) {
        SysUser sysUser = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(sysUser)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }

        //check sign up
        MeetingUserLink where = new MeetingUserLink();
        where.setMeetingId(meetingId);
        where.setPhone(sysUser.getPhone());
        if (!meetingService.checkSignUp(where)) {
            return this.renderJson(MsgOut.error("您还没有报名"));
        }
        meetingService.meetingForSignIn(where);

        return this.renderJson(MsgOut.success());
    }

    /**
     * 效验银行卡名称
     * @param url
     * @return
     */
    @RequestMapping(value = "/api/wap/bankName")
    public String wapEXhTTP(String url) {
        //get请求返回结果
        JSONObject jsonResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.parseObject(strResult);
            } else {
            }
        } catch (IOException e) {

        }
        MsgOut o = MsgOut.success(jsonResult);
        return this.renderJson(o);
    }
    /**
     * 提现申请
     *
     * @param userReward
     * @return
     */
    @RequestMapping(value = "/api/accounts/reward", method = RequestMethod.POST)
    public String rewardForInvite(UserReward userReward,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
//        if (ObjectUtils.isEmpty(userReward)
//                || userReward.getAmount() < 10000) {
//            return this.renderJson(MsgOut.error("100元及以上可以提现。"));
//        }
        //微信提现当天不能超过1万
        if (userReward.getRewardStatus() == 1){
            UserReward ur=new UserReward();
            ur.setUserId(Long.parseLong(userId));
            ur.setRewardStatus((byte)1);
            //获取当天开始时间
            LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
            Long start = today_start.toInstant(ZoneOffset.of("+8")).toEpochMilli();
            //获取当天结束时间
            LocalDateTime today_end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
            Long end = today_end.toInstant(ZoneOffset.of("+8")).toEpochMilli();
            LOGGER.info(start.toString());
            LOGGER.info(end.toString());
            ur.setCtime(start);
            ur.setMtime(end);
            List<UserReward> userRewards=userRewardService.selectUserReward(ur);
            int amount=0;
            if (!ObjectUtils.isEmpty(userRewards)){
                for (UserReward u:userRewards){
                    amount+=u.getAmount();
                }
            }
            amount += userReward.getAmount();
            if (amount > 1000000){
                MsgOut o = MsgOut.error("单日交易额超过10000元上限");
                o.setCode(4);
                return this.renderJson(o);
            }
        }

        //银行卡提现当天不能超过2万
//        if (userReward.getRewardStatus() == 2){
//            UserReward ur=new UserReward();
//            ur.setUserId(Long.parseLong(userId));
//            ur.setRewardStatus((byte)2);
//            //获取当天开始时间
//            LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
//            Long start = today_start.toInstant(ZoneOffset.of("+8")).toEpochMilli();
//            //获取当天结束时间
//            LocalDateTime today_end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
//            Long end = today_end.toInstant(ZoneOffset.of("+8")).toEpochMilli();
//            LOGGER.info(start.toString());
//            LOGGER.info(end.toString());
//            ur.setCtime(start);
//            ur.setMtime(end);
//            List<UserReward> userRewards=userRewardService.selectUserReward(ur);
//            int amount=0;
//            if (!ObjectUtils.isEmpty(userRewards)){
//                for (UserReward u:userRewards){
//                    amount+=u.getAmount();
//                }
//            }
//            amount += userReward.getAmount();
//            if (amount > 2000000){
//                MsgOut o = MsgOut.error("单日交易额超过10000元上限");
//                o.setCode(4);
//                return this.renderJson(o);
//            }
//        }

//        if (ObjectUtils.isEmpty(userReward.getBankId())) {
//            return this.renderJson(MsgOut.error("参数错误{bankId}"));
//        }
        //rewardType 0 个人 ， 1 商家
        UserProfit userProfit = new UserProfit();
        CompanyProfit companyProfit = new CompanyProfit();
        if(userReward.getRewardType() == 0){
            Wallet wallet = walletService.selectByPK(Long.parseLong(userId));
            if (ObjectUtils.isEmpty(wallet)){
                return this.renderJson(MsgOut.error("余额不足 [wallet]"));
            }
            if(userReward.getAmount() > wallet.getUserBalance()){
                return this.renderJson(MsgOut.error("余额不足 []"));
            }
            //扣除提现金额-个人账户
            wallet.setUserBalance(wallet.getUserBalance()-userReward.getAmount());
            walletService.update(wallet);
            userProfit.setUserBalance(wallet.getUserBalance());
        }
        if(userReward.getRewardType() == 1){
            Company company = companyService.selectByUserId(Long.parseLong(userId));
            WalletCompany where = new WalletCompany();
            where.setCompanyId(company.getCompanyId());
            List<WalletCompany> walletCompanies = walletCompanyService.select(where);
            if (ObjectUtils.isEmpty(walletCompanies)){
                return this.renderJson(MsgOut.error("余额不足"));
            }
            where = walletCompanies.get(0);

            if(userReward.getAmount() > where.getCompanyBalance()){
                return this.renderJson(MsgOut.error("余额不足"));
            }
            //扣除提现金额-商家账户
            where.setCompanyBalance(where.getCompanyBalance()-userReward.getAmount());
            walletCompanyService.update(where);
            companyProfit.setCompanyBalance(where.getCompanyBalance());
        }
          //提现申请记录
        if (!ObjectUtils.isEmpty(userReward.getBankCardId())){
            BankCardBag bankCardBag=bankCardBagService.selectByPK(userReward.getBankCardId());
            userReward.setIdCard(bankCardBag.getBankUserIdcard());
            userReward.setRealName(bankCardBag.getBankUserName());
        }else {
            SysUser sysUser =sysUserService.selectByPK(Long.parseLong(userId));
            userReward.setIdCard(sysUser.getIdCard());
            userReward.setRealName(sysUser.getRealName());
        }
           userReward.setUserId(Long.parseLong(userId));
           int amountBefore = userReward.getAmount();
           double companyCommission = 0;
           int profitForTotal = 0;
           double amount = userReward.getAmount() - userReward.getAmount() * 0.006;
           int amountInt = new Long(Math.round(amount)).intValue();
           if(userReward.getRewardType() == 1) {
               Company company1 = companyService.selectByUserId(Long.parseLong(userId));
               CompanyType companyType = companyTypeService.selectByPK(company1.getCompanyTypeId());
               if (companyType.getIndustryId() == 45 || companyType.getIndustryId() == 46 || companyType.getIndustryId() == 47) {
                   amount = userReward.getAmount() + userReward.getAmount() * 0.006;
               }
               CompanyIndustry companyIndustry = companyIndustryService.selectByPK(companyType.getIndustryId());
               companyCommission = Double.parseDouble(companyIndustry.getCompanyCommission());
               profitForTotal = new Long(Math.round((double)(amount * companyCommission) / 100)).intValue();
               userReward.setAmount(userReward.getAmount() - profitForTotal);
               amountInt = new Long(Math.round(userReward.getAmount())).intValue();
               if (companyType.getIndustryId() == 45 || companyType.getIndustryId() == 46 || companyType.getIndustryId() == 47) {
                   //抽成有林的20%
                    Wallet wallet = walletService.selectByPK((long)11701);
                    if(companyCommission > 1) {
                        companyCommission = companyCommission - 0.6;
                        int linMoney = new Long(Math.round((double) (profitForTotal * companyCommission) * 0.2)).intValue();
                        wallet.setUserBalance(wallet.getUserBalance() + linMoney);
                        walletService.update(wallet);

                        //插入用户消费记录
                        UserProfit userProfit1 = new UserProfit();
                        userProfit1.setOrderId(userReward.getRewardId());
                        userProfit1.setMoneyType((byte) 1);
                        userProfit1.setAmount(linMoney);
                        userProfit1.setOrderSn("");
                        userProfit1.setConsumerId(userReward.getUserId());
                        userProfit1.setOrderType((byte) 2);
                        userProfit1.setProfitType((byte) 1);
                        userProfit1.setUserId((long) 11701);
                        userProfit1.setRemark("林的充值卡收益");
                        userProfit1.setUserBalance(wallet.getUserScore());
                        userProfitService.insert(userProfit1);
                    }
               }
           }
           int moneyReduceInt = new Long(Math.round(userReward.getAmount() * 0.006)).intValue();
           userReward.setAmount(amountInt);
           userRewardService.insert(userReward);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date =  df.format(new Date());
        int beforMoney = amountBefore / 100;
        double afterMoney = userReward.getAmount() / 100;
        if(userReward.getRewardType() == 0){
            SysUser sysUser = sysUserService.selectByPK(Long.parseLong(userId));
            buildQRNotify(1,date,beforMoney,afterMoney,sysUser.getNickname());
        } else if(userReward.getRewardType() == 1){
            Company company = companyService.selectByUserId(Long.parseLong(userId));
            if(company.getCompanyTypeId() == 243 || company.getCompanyTypeId() == 244 || company.getCompanyTypeId() == 245){  //充值服务

                String openid = "";
                String certPath = this.getClass().getResource("/").getPath() + "wxpaycert/apiclient_cert.p12";
                if (!ObjectUtils.isEmpty(company)) {
                    WalletCompany walletCompany = walletCompanyService.selectByPK(company.getCompanyId());
                    if (!ObjectUtils.isEmpty(walletCompany)) {

                        //企业自动付款
                        MPService mpService = new MPService();
                        SNSWXUserinfo snswxUserinfo = wxUserinfoService.selectByPK(Long.parseLong(userId));
                        openid = snswxUserinfo.getOpenid();
                        Map<String, Object> rs = null;
                        try {
//                            int moneyForTixian = new Long(Math.round(userReward.getAmount() - userReward.getAmount() * 0.006)).intValue();
                            System.out.println("rewardId == " + userReward.getRewardId());
                            rs = mpService.transfers("" + userReward.getRewardId(), openid, amountInt, API.getClientIpAddress(this.getRequest()), certPath);
                            LOGGER.debug("transfers rs : {}", rs);
                        } catch (Exception e) {
                            return this.renderJson(MsgOut.error("微信支付异常."));
                        }
                        if(ObjectUtils.isEmpty(rs) || ObjectUtils.isEmpty(rs.get("payment_no"))){
                            return this.renderJson(MsgOut.error("微信支付异常: " + rs.get("return_msg")));
                        }
                        if ("SUCCESS".equals(rs.get("return_code").toString())) {
                            userReward.setRemark(rs.get("return_msg").toString());
                            userReward.setPaymentNo(rs.get("payment_no").toString());
                        } else {
                            userReward.setRemark(rs.get("return_msg").toString());
                        }
                        userReward.setRstatus((byte) 1);//已提现
                        userRewardService.update(userReward);
                    }
                }
            }
            buildQRNotify(2,date,beforMoney,afterMoney,company.getCompanyName());
        }
          //个人钱包流水记录
        if (userReward.getRewardType() == 0) {
            userProfit.setOrderId(userReward.getRewardId());
            userProfit.setOrderType((byte)-1);
            userProfit.setAmount(amountBefore);
            userProfit.setUserProfit(userReward.getAmount());
            userProfit.setUserId(Long.parseLong(userId));
            userProfit.setConsumerId(userReward.getUserId());
            userProfit.setMoneyType((byte)1);
            userProfit.setOrderSn(RandomUtils.genOrderSN(userReward.getUserId()));
            userProfit.setMoneyReduce(moneyReduceInt);
            userProfitService.insert(userProfit);
        }
         //商家钱包流水记录
        if (userReward.getRewardType() == 1) {
            companyProfit.setCompanyId(companyService.selectByUserId(Long.parseLong(userId)).getCompanyId());
            companyProfit.setOrderId(userReward.getRewardId());
            companyProfit.setAmount(amountBefore);
            companyProfit.setOrderType((byte)-1);
            companyProfit.setConsumerId(Long.parseLong(userId));
            companyProfit.setOrderSn(RandomUtils.genOrderSN(userReward.getUserId()));
            companyProfit.setCompanyProfit(userReward.getAmount());
            companyProfit.setMoneyReduce(moneyReduceInt);
            companyProfitService.insert(companyProfit);
        }
          return this.renderJson(MsgOut.success(userReward));
    }

    public void buildQRNotify(int type,String date,int beforMoney,double afterMoney,String name) {
        //int[] users = {65446,64970,65155,64956,13};
        int[] users = {65446};
        for(int i = 0;i < users.length;i++){
            TemplateData templateData = TemplateData.New();
            SNSWXUserinfo snswxUserinfo = wxUserinfoService.selectByPK((long)users[i]);
            if (ObjectUtils.isEmpty(snswxUserinfo)) {
                return;
            }
            templateData.setTouser(snswxUserinfo.getOpenid());
            templateData.setTemplate_id("scrlfFQbxiXbiB64d-dBv_uRuhgcxZ9b8SOjkKD9_mA");
            templateData.setTopcolor("FF0000");
            templateData.setData(new TemplateItem());
            if(type == 1){
                templateData.add("first", "您好，个人用户:  "+ name +"  进行提现申请，请尽快处理！提现金额为"
                        + beforMoney + "元，扣除手续费后的金额是" + afterMoney + "元", "#173177");
            } else if(type == 2){
                templateData.add("first", "您好，商家用户:  " + name + "  进行提现申请，请尽快处理！提现金额为"
                        + beforMoney + "元，扣除手续费后的金额是" + afterMoney + "元", "#173177");
            }
            templateData.setUrl(host + "/wap/gxt");
            templateData.add("keyword1", date, "#0044BB");
            templateData.add("keyword2", String.valueOf(beforMoney), "#0044BB");
            templateData.add("remark", "感谢使用首象共享", "#FF3333");
            try {
                LOGGER.info("templateData {}", templateData);
                new MPService().sendAPIEnter4TemplateMsg(templateData);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断是否提现过
     *
     * @return
     */
    @RequestMapping(value = "/api/accounts/checkReward")
    public String checkReward() {
        SysUser sysUser = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(sysUser)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }

        UserReward where = new UserReward();
        where.setUserId(sysUser.getId());
        List<UserReward> rewards = userRewardService.select(where);
        if (ObjectUtils.isEmpty(rewards)){
            return this.renderJson(MsgOut.error());
        }
        return this.renderJson(MsgOut.success());
    }

//    /**
//     * 判断是否绑定了手机
//     */
//    @RequestMapping(value = "/api/accounts/checkBinded", method = RequestMethod.GET)
//    public String checkBinded() {
//        LYSecurityUtil.printRequestInfo();
//        SysUser user = LYSecurityUtil.currentSysUser();
//        if (ObjectUtils.isEmpty(user)) {
//            return this.renderJson(MsgOut.error("Plz login."));
//        }
//
//        SysUser sysUser = sysUserService.selectByPK(user.getId());
//        if (ObjectUtils.isEmpty(sysUser) || StringUtils.isEmpty(sysUser.getPhone())) {
//            return this.renderJson(MsgOut.error());
//        }
//
//        return this.renderJson(MsgOut.success(user.getId()));
//    }

//    /**
//     * 判断是否绑定了手机  手机端登录状态
//     */
//    @RequestMapping(value = "/api/wap/accounts/checkBinded", method = RequestMethod.GET)
//    public String wapCheckBinded(@RequestHeader(value="headId",required = false) String userId) {
//        LYSecurityUtil.printRequestInfo();
//        if (ObjectUtils.isEmpty(userId)) {
//            return this.renderJson(MsgOut.error("Plz login."));
//        }
//
//        SysUser sysUser = sysUserService.selectByPK(Long.parseLong(userId));
//        if (ObjectUtils.isEmpty(sysUser) || StringUtils.isEmpty(sysUser.getPhone())) {
//            return this.renderJson(MsgOut.error());
//        }
//
//        return this.renderJson(MsgOut.success(Long.parseLong(userId)));
//    }
    @RequestMapping(value = "/api/accounts/balance/{userId}")
    public String allBalance(@PathVariable Long userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error());
        }
        SysUser user = sysUserService.selectByPK(userId);
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error());
        }

        Wallet wallet = walletService.selectByPK(userId);
        if(ObjectUtils.isEmpty(wallet)){
            wallet = new Wallet();
            wallet.setUserBalance(0);
            wallet.setUserScore(0);
        }

        Company company = companyService.selectByUserId(userId);
        if (ObjectUtils.isEmpty(company)) {
            wallet.setUserScore(0);
        }else {
            WalletCompany walletCompany = walletCompanyService.selectByPK(company.getCompanyId());
            if (ObjectUtils.isEmpty(walletCompany)) {
                wallet.setUserScore(0);
            }else{
                wallet.setUserScore(walletCompany.getCompanyBalance());
            }
        }
        return this.renderJson(MsgOut.success(wallet));
    }

    @RequestMapping(value = "/api/accounts/openinfo/{userId}")
    public String openinfo(@PathVariable Long userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error());
        }
        SysUser user = sysUserService.selectByPK(userId);
        if (ObjectUtils.isEmpty(user)) {
            return this.renderJson(MsgOut.error());
        }

        SNSWXUserinfo snswxUserinfo = wxUserinfoService.selectByPK(userId);
        if (ObjectUtils.isEmpty(snswxUserinfo)) {
            return this.renderJson(MsgOut.error("帐号异常!"));
        }
        snswxUserinfo.setActivityImageUrl(Configure.appID);
        return this.renderJson(MsgOut.success(snswxUserinfo));
    }

    /**
     * 忘记密码
     * @return
     */
    @RequestMapping(value = "/api/accounts/resetPasswd", method = RequestMethod.POST)
    public String resetPasswd(Long userId) {

        SysUser sysUser = LYSecurityUtil.currentSysUser();
        if (ObjectUtils.isEmpty(sysUser)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if(sysUser.getId() != 1){
            return this.renderJson(MsgOut.error());
        }
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("userId is not empty."));
        }
        SysUser update = sysUserService.selectByPK(userId);
        if (ObjectUtils.isEmpty(update)) {
            return this.renderJson(MsgOut.error("user is empty."));
        }
        update.setPassword(RandomUtils.hashPassword(update.getPhone()));
        sysUserService.update(update);
        return this.renderJson(MsgOut.success("新密码已发送到您的手机"));
    }

}
